package com.ubaer.zsycz.ui.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.lsw.Base.AdapterRefresh;
import com.lsw.util.StringUtil;
import com.ubaer.zsycz.R;
import com.ubaer.zsycz.model.SearchAutoData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class SearchAutoAdapter extends BaseAdapter {
    public static final String SEARCH_HISTORY = "search_history";
    private Context mContext;
    private ArrayList<SearchAutoData> mOriginalValues;// 所有的Item
    public List<SearchAutoData> mObjects;// 过滤后的item
    private final Object mLock = new Object();
    private int mMaxMatch = 10;// 最多显示多少个选项,负数表示全部

    public List<SearchAutoData> getmObjects() {
        return mObjects;
    }

    public SearchAutoAdapter(Context context, int maxMatch, AdapterRefresh adapterRefresh) {
        this.mContext = context;
        this.mMaxMatch = maxMatch;
        this.adapterRefresh = adapterRefresh;
        initSearchHistory();
        mObjects = mOriginalValues;
    }

    @Override
    public int getCount() {
        return mObjects.size();
    }

    @Override
    public Object getItem(int position) {
        return null == mObjects ? 0 : mObjects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        AutoHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.auto_seach_list_item, parent, false);
            holder = new AutoHolder();
            holder.content = convertView
                    .findViewById(R.id.auto_content);
            holder.view_line = convertView
                    .findViewById(R.id.view_line);
            convertView.setTag(holder);
        } else {
            holder = (AutoHolder) convertView.getTag();
        }
        final SearchAutoData data = mObjects.get(position);
        holder.content.setText(data.getContent());
        if (position == mObjects.size() - 1) {
            holder.view_line.setVisibility(View.VISIBLE);
        } else {
            holder.view_line.setVisibility(View.GONE);
        }
        return convertView;
    }

    /**
     * 读取历史搜索记录
     */
    public void initSearchHistory() {
        SharedPreferences sp = mContext.getSharedPreferences(
                SEARCH_HISTORY, 0);
        String longhistory = sp.getString(SEARCH_HISTORY, "");
        String[] hisArrays = longhistory.split(",");
        if (mOriginalValues == null)
            mOriginalValues = new ArrayList<>();
        else mOriginalValues.clear();
//        if (hisArrays.length == 1) {
//            return;
//        }
        for (int i = 0; i < hisArrays.length; i++) {
            if (!StringUtil.isNullOrEmpty(hisArrays[i]))
                mOriginalValues.add(new SearchAutoData().setContent(hisArrays[i]));
        }
        if (mOriginalValues.size() > 0) {
            adapterRefresh.onRefreshAdapter(0, 0);
        } else {
            adapterRefresh.onRefreshAdapter(1, 1);
        }
    }

    /**
     * 匹配过滤搜索内容
     *
     * @param prefix 输入框中输入的内容
     */
    public void performFiltering(CharSequence prefix) {
        if (prefix == null || prefix.length() == 0) {//搜索框内容为空的时候显示所有历史记录
            synchronized (mLock) {
                mObjects = mOriginalValues;
            }
        } else {
            String prefixString = prefix.toString().toLowerCase();
            int count = mOriginalValues.size();
            ArrayList<SearchAutoData> newValues = new ArrayList<SearchAutoData>(
                    count);
            for (int i = 0; i < count; i++) {
                final String value = mOriginalValues.get(i).getContent();
                final String valueText = value.toLowerCase();
                if (valueText.contains(prefixString)) {

                }
                if (valueText.startsWith(prefixString)) {
                    newValues.add(new SearchAutoData().setContent(valueText));
                } else {
                    final String[] words = valueText.split(" ");
                    final int wordCount = words.length;
                    for (int k = 0; k < wordCount; k++) {
                        if (words[k].startsWith(prefixString)) {
                            newValues.add(new SearchAutoData()
                                    .setContent(value));
                            break;
                        }
                    }
                }
                if (mMaxMatch > 0) {
                    if (newValues.size() > mMaxMatch - 1) {
                        break;
                    }
                }
            }
            mObjects = newValues;
        }
        if (mObjects.size() > 0) {
            adapterRefresh.onRefreshAdapter(0, 0);
        } else {
            adapterRefresh.onRefreshAdapter(1, 1);
        }
        notifyDataSetChanged();
    }

    private class AutoHolder {
        TextView content;
        View view_line;
    }

    /**
     * 清除所有历史记录
     */
    public void CleanallSearchHistory() {
        SharedPreferences sp = mContext.getSharedPreferences(SEARCH_HISTORY, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
        mObjects.clear();
        initSearchHistory();
        notifyDataSetChanged();
    }

    /**
     * 清除1项历史记录
     */
    public void CleanSearchHistory(String text) {
        if (StringUtil.isNullOrEmpty(text))
            return;
        SharedPreferences sp = mContext.getSharedPreferences(SEARCH_HISTORY, Context.MODE_PRIVATE);
        String longhistory = sp.getString(SEARCH_HISTORY, "");
        String[] tmpHistory = longhistory.split(",");
        ArrayList<String> history = new ArrayList<String>(
                Arrays.asList(tmpHistory));
        if (history.size() > 0) {
            int i;
            for (i = 0; i < history.size(); i++) {
                if (text.equals(history.get(i))) {
                    history.remove(i);
                    break;
                }
            }
        }
        if (history.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < history.size(); i++) {
                sb.append(history.get(i) + ",");
            }
            sp.edit().putString(SEARCH_HISTORY, sb.toString()).commit();
        } else {
            sp.edit().putString(SEARCH_HISTORY, "").commit();
        }
        initSearchHistory();
    }


    private AdapterRefresh adapterRefresh;
}
